<?php

namespace app\user\model;

use think\Model;
use app\common\traits\model\TraitModel;
use Carbon\Carbon;
use Exception;
use think\Log;
use Sanyc\Aliyun\AliyunEmail;
class Orders extends Model
{
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime         = 'created_at';
    protected $updateTime         = 'updated_at';
    protected $table              = 'orders';
	protected $type = [
		'rent_contact_id' => 'array',
	];
    const ORDER_OBLIGATION_STATUS     = 100;//未支付
    const ORDER_STAYIN_STATUS         = 101;//待入住
    const ORDER_REFUND_STATUS         = 102;//退款中(待入住取消订单)
    const ORDER_CANCEL_STATUS         = 103;//取消订单
    const ORDER_ONGOING_STATUS        = 104;//支付中
    const ORDER_CHECKIN_STATUS        = 200;//入住中
    const ORDER_LEAVE_STATUS          = 201;//已离开
    const ORDER_REFUND_DEPOSIT_STATUS = 202;//返还押金中
    const ORDER_DONE_STATUS           = 203;//已完成
    const MAX_DIFF_DAYS               = 7;

    private $payment_type = ['wx_pay' => '微信支付', 'al_pay' => '支付宝'];

    use TraitModel;
	

    public function getStatusAttr($value)
    {
        $status = [
            100 => '未支付',
            101 => '待入住',
            102 => '退款中',
            103 => '取消订单',
            104 => '支付中',
            200 => '入住中',
            201 => '已离开',
            202 => '返还押金',
            203 => '已完成'
        ];
        return $status[$value];
    }

    /**
     * 根据订单信息获取用户信息
     * @return [type] [description]
     */
    public function user()
    {
        //return $this->hasOne('Users', 'id', 'caravan_user_id');
    }
    /**
     * 根据订单信息获取房车信息
     * @return [type] [description]
     */
    public function caravan()
    {
        return $this->belongsTo('Caravans','caravan_id');
    }
    /**
     * 根据订单信息获取营地信息
     * @return [type] [description]
     */
    public function camp()
    {
        return $this->belongsTo('Camps','camp_id');
    }
    protected function notifys($msg, $order_info)
    {
        $user = self::getLoginUserInfo();
        if ($user->open_id && $user->oauth_type == 'wx') {
            $notice = new \app\common\Notice();
            $data = array(
                     "first"  => '您的车辆已经预定成功',
                     "OrderID"   => $order_info->number,
                     "PersonName" => '',
                     "PickupDate" => $order_info->take_car_date,
                     "DropoffDate" => $order_info->leave_car_date,
                     "CarType" => '房车',
                     "PaymentType" => '暂定',
                     "remark" => "订单将为您保留1小时，请尽快完成支付",
                    );
            $notice->setTemplate('ordercreate')->send($user->open_id, $data, 'http://wx.shsytour.cn/order/show?order_id=' . $order_info->number);
        }
        model('Notifys')->createNotifys(['users_id' => $user->id, 'body' => $msg]);
    }
    /**
     * 获取订单
     * @param array $query 查询条件
     * @return [type] [description]
     */
    public function getOrders($query = [], $order = 'updated_at desc')
    {
        return $this->setPageSize(4)->getInfoList(array_merge($query, ['rent_user_id' => self::getLoginUserInfo('id')]), $order);
    }
    /**
     * 获取订单详情信息
     * @param  string|array $where [description]
     * @return [type]           [description]
     */
    public function getOrderInfo($where)
    {
    	return $this->get($where);
    }
    /**
     * 生成订单SN
     * @return [type] [description]
     */
    public function createOrderId()
    {
        return $this->getBusiness() . substr(time(), 0, 8) . substr(str_shuffle(str_repeat('0123456789', 6)), 0, 6);
    }
    /**
     * 获取业务来源
     * @return [type] [description]
     */
    private function getBusiness()
    {
        return 10;
    }
    /**
     * 创建订单
     * @param  [type] $order_info [description]
     * @return [type]             [description]
     */
    protected function createOrder($order_info)
    {
        if ($order = self::create($order_info, true)) {
            $this->notifys('你的订单' . $order->number . '已生成请尽快完成支付', $order);
            return $order;
        }
    }
    /**
     * 生成分享订单
     * @param  [type] $order_info [description]
     * @return [type]             [description]
     */
    public function createShareOrder($order_info)
    {
        $this->startTrans();
        try {
            $order = $this->createOrder($order_info);
            $this->setCaravanCarlendarIsOrders($order_info['caravan_id'], $order_info['take_car_date'], $order_info['leave_car_date'], ['orders' => ['not in', '0'], 'shares' => 1, 'wishs' => 0]);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return $order;
    }
    /**
     * 生成出租订单
     * @param  [type] $order_info [description]
     * @return [type]             [description]
     */
    public function createRentOrder($order_info)
    {
        $this->startTrans();
        try {
            $order = $this->createOrder($order_info);
            $this->setCaravanCarlendarIsOrders($order_info['caravan_id'], $order_info['take_car_date'], $order_info['leave_car_date'], ['orders' => ['not in', '0'], 'rents' => 1, 'wishs' => 0]);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return $order;
    }
    /**
     * 生成心愿悬赏订单
     * @param  [type] $order_info [description]
     * @return [type]             [description]
     */
    public function createWishOrder($order_info)
    {
        $this->startTrans();
        try {
            $order = $this->createOrder($order_info);
            $this->setCaravanCarlendarIsOrders($order_info['caravan_id'], $order_info['take_car_date'], $order_info['leave_car_date'], ['orders' => ['not in', '0'], 'wishs' => 1]);
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
        return $order;
    }
    /**
     * 设置房车状态
     * @param [type]  $caravan_id [description]
     * @param [type]  $start_date [description]
     * @param [type]  $end_date   [description]
     * @param integer $status     [description]
     * @param array   $querys     [description]
     * @param boolean $syn        [description]
     */
    private function setCaravanCarlendarIsOrders($caravan_id, $start_date, $end_date, $querys = ['orders' => ['not in', '0']], $syn = false)
    {
        return model('user/Calendar')->setUserCaravanCarlendarIsOrders($caravan_id, $start_date, $end_date, '', $querys, $syn);
    }
    /**
     * 订单消费扣除积分
     * @param  [type] $intergrate [description]
     * @param  string $remark     [description]
     * @return [type]             [description]
     */
    public function reduceIntergrate($intergrate, $user_id, $remark = '订单消费')
    {
        return model('Intergrates')->reduceIntergrates($intergrate, $user_id, ['remark' => $remark]);
    }
    /**
     * 订单完成
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    public function orderCompletion($order_id)
    {
        if ($order = $this->getOrderInfo(['number' => $order_id, 'rent_user_id' => self::getLoginUserInfo('id')])) {
            $this->startTrans();
            try {
                switch ($order->source) {
                    case 2:
                        //出租
                        //对方用户资金增加
                        model('Capitals')->incCapital($order->total_intergral, $order->caravan_user_id);
                        break;
                    case 3:
                        //心愿悬赏
                        //对方用户积分资金增加
                        model('Capitals')->incCapital($order->total_money, $order->caravan_user_id);
                        model('Intergrates')->addIntergrates($order->total_intergral, $order->caravan_user_id);
                        break;
                }
                $order->status = self::ORDER_CHECKIN_STATUS;
                $order->save();
                $this->commit();
            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
            return true;
        }
        return false;
    }
    /**
     * 完成订单支付
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    public function completeOrderPay($order_id)
    {
        if ($order = $this->getOrderInfo(['number' => $order_id])) {
            $this->startTrans();
            try {
                //判断是否需要扣除积分
                // if ($order->total_intergral > 0) {
                //     $this->reduceIntergrate($order->total_intergral, $order->rent_user_id);
                // }
                
                model('Messages')->createMsg($msg_info = ['users_id' => $order->rent_user_id, 'body' => '一切就绪,您预订的房车正等待您的入住!']);
                model('Messages')->createMsg($msg_info = ['users_id' => $order->caravan_user_id, 'body' => '感谢您的分享,您的房车被预订了,请您即时将房车钥匙递交给管理员!']);
                
                $order->status = self::ORDER_STAYIN_STATUS;//完成支付进入待入住
                $order->paid_at = Carbon::now()->toDateTimeString();//支付时间
                
                $order->save();
                $this->commit();
            } catch (\Exception $e) {
                Log::record($d);
                $this->rollback();
                return false;
            }
            // queue('app\common\job\JobPay@sendEmailTest', ['number'=>$order_id,'qufen'=>'user'], $delay = 0, $queue = 'order');
            // queue('app\common\job\JobPay@sendEmailTest', ['number'=>$order_id,'qufen'=>'car'], $delay = 0, $queue = 'order');
            // queue('app\common\job\JobPay@sendEmailTest', ['number'=>$order_id,'qufen'=>'camp'], $delay = 0, $queue = 'order'); 
            $this->sendWhichUser($order_id);
            return true;
        } 
        return false;
    }
    /**
     * [sendWhichUser 发送邮件]
     * @param  [type] $type         [description]
     * @param  [type] $order_number [description]
     * @return [type]               [description]
     */
    public function sendWhichUser($order_number)
    {
        $theme = '双辉旅程网';
        $o_t = ['1'=>'出租','2'=>'交换'];
        $orderinfo  = model("Orders")->where('number',$order_number)->find();
        $type       = $orderinfo->source;
        $xia_dan    = $orderinfo->created_at;//halt($xia_dan);
        $start_date = $orderinfo->take_car_date;
        $end_date   = $orderinfo->leave_car_date;
        try {
        //车主邮箱
        $car_email = db('users')->where('id',$orderinfo->caravan_user_id)->value('email');
        $content1  = <<<data
尊敬的会员，您的房车于 $xia_dan 被他人下单。$o_t[$type]日期是 $start_date 至 $end_date 。
data;
        $this->sendEmail($car_email,$theme,$content1);
        //下单人邮箱
        $user_email = db('users')->where('id',$orderinfo->rent_user_id)->value('email');
        $content2  = <<<data
尊敬的会员，您于 $xia_dan 下单并支付成功。$o_t[$type]日期是 $start_date 至 $end_date ,祝您旅途愉快。
data;
        $this->sendEmail($user_email,$theme,$content2);
        //通知营地信息
        $camp_email = db('camps')->where('id',$orderinfo->camp_id)->value('email');
        $car_name = db('caravan')->where('id',$orderinfo->caravan_id)->value('name');
        $content3  = <<<data
尊敬的营地管理员， 于 $xia_dan ,该营地房车：$car_name 被他人预定 。预定日期是 $start_date 至 $end_date 。
data;
        $this->sendEmail($camp_email,$theme,$content3);
        }catch (\Exception $e) {

        }
    }
    /**
     * [sendEmail 发送邮箱]
     * @param  [type] $emailAddress [目标邮箱]
     * @param  [type] $theme        [邮件主题]
     * @param  [type] $content      [邮件内容]
     * @return [type]               [description]
     */
    public function sendEmail($emailAddress,$theme,$content)
    {
        $mail = AliyunEmail::init(config('mail'))->send($emailAddress, $theme, $content);
        return $mail;
    }
    /**
     * 取消订单
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    public function cancelOrder($order_id)
    {
        $user_id = self::getLoginUserInfo('id');
        if (!$order = $this->getOrderInfo(['number' => $order_id, 'rent_user_id' => $user_id])) {
            return false;
        }

        if ($order->getData('status') == self::ORDER_OBLIGATION_STATUS) {
            //未支付
            $this->startTrans();
            try {
                $time = model('Calendar')->delordered($order->caravan_id, $order_id, $order->take_car_date, $order->leave_car_date);//同步日历
                $order->status = self::ORDER_CANCEL_STATUS;//取消状态
                $order->save();
                $this->commit();
                return true;
            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
        }

        if ($order->getData('status') == self::ORDER_ONGOING_STATUS) {
            //未支付取消订单返回旅行币
            $this->startTrans();
            try {
                $user_id = $order->rent_user_id;
                $user_info = model('Users')->where('id',$user_id)->find();
                $user_info->integral = $user_info->integral + $order->total_intergral;
                $user_info->save();//取消订单加旅行币
                $time = model('Calendar')->delordered($order->caravan_id, $order_id, $order->take_car_date, $order->leave_car_date);//同步日历
                $order->status = self::ORDER_CANCEL_STATUS;//取消状态
                $order->save();
                $this->commit();
                return true;
            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
        }

        if ($order->getData('status') == self::ORDER_STAYIN_STATUS) {
            //支付订单
            $this->startTrans();
            try {
                $sanction = $this->orderSanction($order);
                //写入退款流水
                $this->quitDeposit($order, $sanction['integral'], $sanction['currency']);
                //$this->backIntergrate($order, $sanction);
                $time = model('Calendar')->delordered($order->caravan_id, $order_id, $order->take_car_date, $order->leave_car_date);//同步日历
                $order->status = self::ORDER_REFUND_STATUS;//退款中状态
                $order->save();
                $this->commit();
                return true;
            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
        }
        
    }
    /**
     * 订单处罚
     * @param  [type] $order [description]
     * @return [type]        [description]
     */
    protected function orderSanction($order)
    {
        $sanction  = ['integral' => 0, 'currency' => 0];
        $integral  = $order->total_intergral;
        $currency  = $order->total_money;
        $today     = Carbon::today()->toDateString();
        $checkDate = $order->take_car_date;
        $diffDays  = $this->diffDays($today, $checkDate, false);

    	// if (self::MIN_DIFF_DAYS < $diffDays && $diffDays < self::MAX_DIFF_DAYS) {
    	// 	$sanction['integral'] = $integral * 0.1;
    	// 	$sanction['currency'] = $currency * 0.1;
    	// }elseif ($diffDays < self::MIN_DIFF_DAYS) {
    	// 	$sanction['integral'] = $integral * 0.2;
    	// 	$sanction['currency'] = $currency * 0.2;
    	// }
        if ($diffDays < self::MAX_DIFF_DAYS) {
            $sanction['integral'] = $integral * 0.5;
            $sanction['currency'] = $currency * 0.5;
        }
        return $sanction;
    }
    /**
     * 获取订单状态
     * @param  [type] $order_id [description]
     * @return [type]           [description]
     */
    public function getOrderStatus($order_id)
    {
    	if ($order = $this->getOrderInfo($order_id)) {
    		return $order->status;
    	}
    	return false;
    }
    /**
     * 更改订单状态
     * @param [type]  $order_id [description]
     * @param integer $status   [description]
     */
    public function setOrderStatus($order_id, $status = self::ORDER_OBLIGATION_STATUS)
    {
        if (is_numeric($order_id) || is_string($order_id)) {
            $id = $order_id;
        } elseif ($order_id instanceof Model) {
            $order_id->status = $status;
            $order_id->save();  
        }else{
            return false;
        }
        if (isset($id)) {
            $this->update(['status' => $status], ['number' => $order_id, 'rent_user_id' => self::getLoginUserInfo('id')], true);
        }
        return true;
    }
    /**
     * 返还积分
     * @param [type]  $order_id [description]
     * @param integer $status   [description]
     */
    protected function backIntergrate($order, $sanction)
    {
        $intergrate = $order->total_intergral -$sanction['integral'];//halt($intergrate);
        $remark = '取消订单返还旅行币';
        return model('Intergrates')->addIntergrates($intergrate, $user_id = null, ['remark' => $remark]);

    }
    protected function reduceIntergrates($intergrate, $users_id)
    {
        model('Intergrates')->reduceIntergrates($intergrate, $users_id, ['remark' => '取消订单处罚'], $abs = false);
    }
    /**
     * 写入退款流水
     * @param  [type] $order      [description]
     * @param  [type] $intergrate 惩罚的积分
     * @param  [type] $deposit    惩罚的金钱
     * @return [type]             [description]
     */
    private function quitDeposit($order, $intergrate = 0, $deposit = 0)
    {
        if (0 == model('QuitDeposit')->where(['number' => $order->number])->Count()) {
            $intergrate = $order->total_intergral - $intergrate;
            $deposit    = $order->total_money + $order->deposit - $deposit;
            model('QuitDeposit')->createQuitDeposit([
                'user_id'    => $order->rent_user_id, 
                'number'     => $order->number, 
                'intergrate' => $intergrate, 
                'deposit'    => $deposit,
                'describe'   => '取消订单退款'
            ]);
        }
    }
    /**
     * 返还现金
     * @param [type]  $order_id [description]
     * @param integer $status   [description]
     */
    public function FunctionName($value='')
    {
        # code...
    }

	/**
	 * 心愿订单获取总旅行币
	 * @param $start_date 开始时间
	 * @param $end_date 结束时间
	 * @param $travel_money_base 营地旅行币基数
	 */
	public function getTotalCoin($start_date,$end_date,$travel_money_base){
		//获取日期范围
	  	$array_date = $this->createDateRange($start_date,$end_date);
		//获取每天的假日系数
		$array_coefficient = $this->getCoefficient($array_date);
		//$array_coefficient = [1.2,1.5];
		//总旅行币
        $intergral = $travel_money_base*array_sum($array_coefficient);
        return $intergral;
	}
	
	/**
	 * 自动取消未付款心愿订单
	 * @param $number 取消的条件
	 */
	public function cancelWishOrder($number,$wid){
		
		$user_id = self::getLoginUserInfo('id');
        if (!$order = $this->getOrderInfo(['number' => $order_id, 'rent_user_id' => $user_id])) {
            return false;
        }
        if ($order->getData('status') == self::ORDER_OBLIGATION_STATUS) {
            //未支付
            $this->startTrans();
            try {
                $time = model('Calendar')->delordered($order->caravan_id, $order_id, $order->take_car_date, $order->leave_car_date);//同步日历
                $order->status = self::ORDER_CANCEL_STATUS;//取消状态
                $order->save();
                $this->commit();
            } catch (Exception $e) {
                $this->rollback();
                return false;
            }
		}
        return true;
	} 
}
